package com.easyj.admin.person.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.easyj.admin.db.model.Position;
import com.easyj.admin.db.model.Role;
import com.easyj.admin.db.model.User;
import com.easyj.admin.sys.service.PermissionService;
import com.easyj.admin.sys.service.UserService;
import com.easyj.base.common.ajax.Result;
import com.easyj.base.common.storage.FileInfo;
import com.easyj.base.controller.BaseController;
import com.easyj.base.exception.FileStoreException;
import com.easyj.base.security.AuthInfoDTO;
import com.easyj.base.security.SimpleUser;
import com.easyj.base.security.UserDTO;
import com.easyj.base.storage.service.StorageService;

/**
 * 个人中心
 * @author hjf
 */

@RestController
@RequestMapping(value = "/person")
public class PersonController extends BaseController{
	
	@Autowired 
	private   PermissionService permissionService;

	@Autowired 
	private   UserService userService;
	
	@Autowired
	private  StorageService storageService;
	
		
	
	/**
	 *    用户登录后取菜单\用户信息\权限
	 * @return
	 */
	@GetMapping(value = "routes")
	public Result getRoutes() {
		try {
			SimpleUser us=(SimpleUser)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
			//权限、角色
			 AuthInfoDTO auth=new AuthInfoDTO();
		     ArrayList<String> authlist=new ArrayList<String>();
		     if(us.getAuthorities()!=null) {
		    	 for(GrantedAuthority g:us.getAuthorities()) {
		    		 authlist.add(g.getAuthority());
		    	 }
		     }
		     auth.setAuthorities(authlist);
		     
		     List<Role> roles=userService.findRolesByUserId(us.getId());
		     auth.setRoles(roles);
		     
		     List<Position> positions=userService.findPositionsByUserId(us.getId());
		     auth.setPositions(positions);
		     
		     //用户基本信息
		     UserDTO u=new UserDTO();
		     u.setId(us.getId());
		     u.setDepartmentId(us.getDepartmentId());
		     u.setName(us.getName());
		     u.setLoginName(us.getLoginName());			 
			 
			 auth.setUser(u);
			 
			 //更多用户信息
			 User more=userService.findByCache(us.getId());
			 
			 u.setQq(more.getQq());
			 u.setEmail(more.getEmail());
			 u.setSex(more.getSex());
			 u.setMobile(more.getMobile());
			 u.setTelephone(more.getTelephone());
			 u.setDuty(more.getDuty());
			 u.setAvatar(more.getAvatar());
			 
	         
			 
			 //路由菜单
			 auth.setRoutes(permissionService.getUserRouteTree());
			 return Result.Success(auth);
		}catch(Exception ex) {
			log.error("/person/menus", ex);
			return Result.Error("读取用户限信息错误！");
		}
	}
	
	
	@PostMapping(value = "changePassword")
	public Result changePassword(@RequestParam(value = "password") String password) {
		if(password==null||password.length()>18||password.length()<6) {
			return Result.Error("密码不符合要求");
		}
		/*/正则表达式，数字与字母组成
		String regex = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,18}$";
		if(!password.matches(regex)) {
			return Result.Error("密码不符合要求");
		}
		*/
		User u=new User();
		u.setId(this.getUserId());
		u.setPassword(password);
		userService.changePassword(u);
		
		return Result.Success();
	}
	
	
	@RequestMapping(value = "saveAvatar", method = RequestMethod.POST)
	public Result saveAvatar(@RequestParam MultipartFile file){ //参数名：file
		try {
			FileInfo result=storageService.storeAvatarFile(file);
			User entity = new User();
			entity.setId(this.getUserId());
			entity.setAvatar(result.getUrl());
			userService.updateAvatar(entity);
			return Result.Success(result);
		} catch (FileStoreException e) {
			return Result.Error("上传头像失败！");
			//e.printStackTrace();
		}	
	}
	
	@RequestMapping(value = "updatePersonInfo", method = RequestMethod.POST)
	public Result updatePersonInfo(@RequestBody  User entity) {
		try{
			entity.setId(this.getUserId());
			userService.updatePersonInfo(entity);
			return Result.Success();
		}catch(Exception ex){
			log.error("UserController.add", ex);
			return Result.Error(ex.getMessage()); 
		}
	}
}
